/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.worlds.object;

import java.util.logging.Level;
import java.util.logging.Logger;
import net.worlds.WorldsException;
import net.worlds.Main;
import net.worlds.PropChangeHandler;
import net.worlds.Util;
import net.worlds.net.Client;
import net.worlds.ui.UI;
import se.krka.kahlua.vm.JavaFunction;
import se.krka.kahlua.vm.LuaCallFrame;


public class NetworkClient extends GameObject{
    private int port;
    private String ip;
    private Client client;
    public NetworkClient() throws WorldsException
    {
        super("NetworkClient");
        addPropChangeHandler("IP", new PropChangeHandler()
        {

            @Override
            public void handle(Object oldValue, Object value) throws WorldsException {
                ip = value.toString();
            }
        });
        addPropChangeHandler("Port", new PropChangeHandler()
        {

            @Override
            public void handle(Object oldValue, Object value) throws WorldsException {
                if(Util.isInteger(value.toString()))
                    port = Integer.parseInt(value.toString());
            }
        });
        addPropChangeHandler("LocalPlayer", new PropChangeHandler()
        {
            @Override
            public void handle(Object oldValue, Object value) throws WorldsException {
                Main.setLocalPlayer((Player) value);
            }

        });
        //x_;
        addFunction("start", new JavaFunction()
        {

            public int call(LuaCallFrame callFrame, int nArguments) {
                try {
                    String ip = (String) callFrame.get(1);
                    double port = (Double) callFrame.get(2);
                    setProp("IP", ip, true);
                    setProp("Port", (int) port, true);
                    start();
                } catch (WorldsException ex) {
                    Logger.getLogger(NetworkClient.class.getName()).log(Level.SEVERE, null, ex);
                }
                return 0;
            }

        });
    }
    @Override
    public void addToWorld() throws WorldsException
    {
        super.addToWorld();
    }
    public void start()
    {
        Main.runInMainThread(new Runnable()
        {

            public void run() {
                UI.mouseMode = UI.MODE_NONE;
                Main.setClientObject((NetworkClient) instance);
                Main.setLoading(true);
                Main.getGame().getCurrentWorld().setMessage("Connecting...");
                client = new Client((NetworkClient) instance, ip, port);
                Main.setClient(client);
            }
        });
    }
}
